package com.nlp.trie.bigramSeg;

import java.util.Iterator;

/**
 * 邻接矩阵表示的切分词图
 * @author ygsong.abcft
 *
 */
public class AdjList implements Iterable<CnToken>{
	
	private CnTokenLinkedList list[];//AdjList的图的结构
	private int verticesNum;
	
	/**
	 * 初始化
	 * @param verticesNum
	 */
	public AdjList(int verticesNum) {
		this.verticesNum = verticesNum;
		list = new CnTokenLinkedList[verticesNum];
		
		for (int index = 0; index < verticesNum; index++) {
			list[index] = new CnTokenLinkedList();
		}
		
	}
	

	/**
	 * 添加到图中
	 * @param newEdge
	 */
	public void addEdge(CnToken newEdge) {
		list[newEdge.end].put(newEdge);
	}
	
	/**
	 * 返回包含通向相邻节点的边的迭代器。
	 * @param vertex
	 * @return
	 */
	public Iterator<CnToken> getPrev(int vertex){
		CnTokenLinkedList ll = list[vertex];
		if (ll == null) {
			return null;
		}
		return ll.iterator();
	}
	
	@Override
	public String toString() {

		StringBuilder temp = new StringBuilder();

		for (int index = 0; index < verticesNum; index++) {
			if(list[index] == null)
			{
				continue;
			}
			temp.append("node:");
			temp.append(index);
			temp.append(": ");
			temp.append(list[index].toString());
			
			temp.append("\n");
		}

		return temp.toString();
	
	}
	@Override
	public Iterator<CnToken> iterator() {
		return new AdjIterator();
	}
	
	private class AdjIterator implements Iterator<CnToken>{
		int pos;
		Iterator<CnToken> it;
		public AdjIterator() {
			pos = 1;//去掉开始节点
			it = list[pos].iterator();
		}
		
		public boolean hasNext() {
			if (it.hasNext()) {
				return true;
			}
			while (pos < (verticesNum - 1)) {
				pos++;
				it = list[pos].iterator();
				if (it.hasNext()) {
					return true;
				}
			}
			return false;
		}
		
		public CnToken next() {
			if (!hasNext()) {
				return null;
			}
			CnToken t = it.next();
			return t;
		}
	}
	
	public CnTokenLinkedList prevWordList(int start) {
		if (start < 0) {
			return null;
		}
		return list[start];
	}

}
